/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 18/10/2004
 *
 */

package au.com.lastweekend.jim.imagebase;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.metadata.Directory;

/**
 * @author grant@lastweekend.com.au
 * @version $Id: ImageBaseDirectory.java,v 1.6 2006/03/01 09:52:04 ggardner Exp $
 */
public final class ImageBaseDirectory extends Directory {

    private static final long serialVersionUID = -1914608487168305935L;

    public static final int TAG_FILENAME = 1;
    public static final int TAG_TITLE = 2;
    static final int TAG_PATHS = 3;
    static final int TAG_KEYWORDS = 4;

    public static final int FMT_STRING = 0;
    public static final int FMT_STRING_SET = 2;
    static final int FMT_FILE_SET = 4;

    private static final HashMap<Integer, String> TAG_NAME_MAP = new HashMap<Integer, String>();

    private TagHandler _tagHandler = TagHandler.NOOP_TAG_HANDLER;
    private static final Logger LOG = Logger.getLogger(ImageBaseDirectory.class);

    static {
        TAG_NAME_MAP.put(TAG_FILENAME, "Filename");
        TAG_NAME_MAP.put(TAG_TITLE, "Title");
        TAG_NAME_MAP.put(TAG_PATHS, "Paths");
        TAG_NAME_MAP.put(TAG_KEYWORDS, "Keywords");
    }

    public ImageBaseDirectory() {

        super(null);
        this.setDescriptor(new ImageBaseDescriptor(this));
        setTitle("");
        Set<File> emptySetOfFile = new HashSet<File>();
        setPaths(emptySetOfFile);
        Set<String> emptySetOfString = new HashSet<String>();
        setKeywords((emptySetOfString));
    }

    /*
     * @see au.com.lastweekend.jim.io.metadata.Directory#getName()
     */
    @Override
    public String getName() {

        return "Image Base";
    }

    /*
     * @see au.com.lastweekend.jim.io.metadata.Directory#getTagNameMap()
     */
    @Override
    protected Map<Integer, String> getTagNameMap() {

        return TAG_NAME_MAP;
    }

    public TagHandler getTagHandler() {

        return _tagHandler;
    }

    public void setTagHandler(TagHandler tagHandler) {

        _tagHandler = tagHandler;
    }

    public String getFilename() {

        return getString(TAG_FILENAME);
    }

    /**
     * @param name
     */
    public void setFilename(String name) {

        setTag(TAG_FILENAME, FMT_STRING, name);

    }

    @Override
    public void removeTag(int tagType) {

        // TODO remove from ImageBase...
        super.removeTag(tagType);
    }

    @Override
    public void setTag(int tagType, int formatCode, Object value) {

        super.setTag(tagType, formatCode, value);
        getTagHandler().setTag(tagType, formatCode, value);
    }

    /**
     * Note the lack of real type safety here. Is there a way to genericise this as the directory generally contains a Map of
     * Object, so the cast has to happen somewhere and a cast to Set<File> is actually a cast to Set.
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    Set<File> getPaths() {

        return Collections.unmodifiableSet((Set) getObject(TAG_PATHS));

    }

    public Set<String> getKeywords() {

        return Collections.unmodifiableSet(getKeywordsAsSetString());

    }

    @SuppressWarnings("unchecked")
    private Set<String> getKeywordsAsSetString() {

        return (Set) getObject(TAG_KEYWORDS);
    }

    public Set<File> getFiles() {

        Set<File> files = new HashSet<File>();
        for (File filePath : getPaths()) {
            files.add(new File(filePath, getFilename()));
        }
        return Collections.unmodifiableSet(files);
    }

    public void addFile(File imageFile) {

        Set<File> oldPaths = getPaths(); // an unmodifiable set!
        Set<File> newPaths = new HashSet<File>(oldPaths);

        File parent = getImageBaseParent(imageFile);
        if (newPaths.add(parent)) {
            setPaths(newPaths);
        }

    }

    public void removeFile(File expectedFile) {

        Set<File> oldPaths = getPaths(); // an unmodifiable set!
        Set<File> newPaths = new HashSet<File>(oldPaths);

        File parent = getImageBaseParent(expectedFile);
        if (newPaths.remove(parent)) {
            setPaths(newPaths);
        }

    }

    public void setPaths(Set<File> newPaths) {

        setTag(TAG_PATHS, FMT_FILE_SET, newPaths);
    }

    public String getTitle() {

        return getString(TAG_TITLE);
    }

    public void setTitle(String title) {

        if (title == null) {
            removeTag(TAG_TITLE);
        } else {
            setTag(TAG_TITLE, FMT_STRING, title);
        }
    }

    public void setKeywords(Set<String> keywords) {

        setTag(TAG_KEYWORDS, FMT_STRING_SET, keywords);

    }

    /**
     * @param imageFile
     * @return the parent file in the same format as it will be stored in the ImageBase
     */
    public static File getImageBaseParent(File imageFile) {

        if (imageFile == null) {
            return null;
        } else {
            return convertToImageBaseFile(imageFile.getParentFile());
        }
    }

    /**
     * @param parent
     * @return canonical format of imagebase parent path for storage and searching
     */
    public static File convertToImageBaseFile(File parent) {

        if (parent != null) {
            parent = parent.getAbsoluteFile();

            try {
                parent = parent.getCanonicalFile();
            } catch (IOException e1) {
                LOG.warn("Problem getting canonical file", e1);
            }
        }
        return parent;
    }

    @Override
    public String toString() {

        return getFilename();
    }
}